package com.geek.game.manager.agent.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.geek.game.manager.agent.base.Constants;
import com.geek.game.manager.agent.base.mvc.BaseController;
import com.geek.game.manager.agent.base.mvc.WorkException;
import com.geek.game.manager.agent.base.utils.DateTimeUtil;
import com.geek.game.manager.agent.base.utils.JacksonUtil;
import com.geek.game.manager.agent.base.utils.MD5Util;
import com.geek.game.manager.agent.model.Club;
import com.geek.game.manager.agent.model.ClubPlayerMapping;
import com.geek.game.manager.agent.model.Manager;
import com.geek.game.manager.agent.model.Player;
import com.geek.game.manager.agent.service.ClubService;

import ydh.cicada.dao.JdbcDao;
import ydh.cicada.query.QueryObject;
import ydh.cicada.service.CommonService;

@Controller
@RequestMapping(value="main")
public class MainController extends BaseController {

	@Autowired
	private ClubService clubService;
	@Autowired
	private JdbcDao dao;
	
	@RequestMapping(value="index", produces = "text/html;charset=utf8")
	public String main(Model model){
		model.addAttribute("titleName", "代理后台");
		
		return "main";
	}
	/**
	 * 成员管理
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getSubAgent", produces = "text/html;charset=utf8")
	public String getSubAgent(Model model){
		model.addAttribute("titleName", "成员管理");
		Manager user=(Manager)session.getAttribute(request.getLocalAddr());
		if(user!=null && StringUtils.isNotBlank(user.getId())){
			List<Club> clubs=clubService.selectClubListByManagerId(user.getId());
			model.addAttribute("clubs",clubs);
			model.addAttribute("user", user);
		}
		return "subAgent";
	}
	/**
	 * 下级管理
	 * @param model
	 * @return
	 */
	@RequestMapping(value="getSubManager", produces = "text/html;charset=utf8")
	public String getAgentManager(Model model){
		model.addAttribute("titleName", "下级管理");
		Manager user=(Manager)session.getAttribute(request.getLocalAddr());
		if(user!=null && StringUtils.isNotBlank(user.getId())){
			model.addAttribute("user", user);
			model.addAttribute("userJSON",JacksonUtil.getJsonFromObject(user));
		}
		return "member";
	}
	
	
	@RequestMapping(value="billContro", produces = "text/html;charset=utf8")
	public String billContro(Model model){
		model.addAttribute("titleName", "账单管理");
		Manager user=(Manager)session.getAttribute(request.getLocalAddr());
		if(user!=null && StringUtils.isNotBlank(user.getId())){
			List<Club> clubs=clubService.selectClubListByManagerId(user.getId());
			model.addAttribute("clubs",clubs);
			model.addAttribute("clubsJSON", JacksonUtil.getJsonFromObject(clubs));
			model.addAttribute("user", user);
			model.addAttribute("userJSON",JacksonUtil.getJsonFromObject(user));
		}
		return "billContro";
	}
	
	@RequestMapping(value="stock", produces = "text/html;charset=utf8")
	public String stock(Model model){
		model.addAttribute("titleName", "进货");
		Manager user=(Manager)session.getAttribute(request.getLocalAddr());
		if(user!=null && StringUtils.isNotBlank(user.getId())){
			List<Club> clubs=clubService.selectClubListByManagerId(user.getId());
			model.addAttribute("clubs",clubs);
			model.addAttribute("clubsJSON", JacksonUtil.getJsonFromObject(clubs));
			model.addAttribute("user", user);
			model.addAttribute("userJSON",JacksonUtil.getJsonFromObject(user));
		}
		return "stock";
	}
	@RequestMapping(value="dayRecord", produces = "text/html;charset=utf8")
	public String dayRecord(Model model){
		model.addAttribute("titleName", "进货");
		Manager user=(Manager)session.getAttribute(request.getLocalAddr());
		if(user!=null && StringUtils.isNotBlank(user.getId())){
			Integer totalSaleNumber=QueryObject.select("sum(t.mahjong_coin)", Integer.class).from("t_recharge_record t").cond("t.user_id").equ(user.getId()).uniqueResult(dao);
			model.addAttribute("totalSaleNumber",totalSaleNumber);
			model.addAttribute("user", user);
			model.addAttribute("userJSON",JacksonUtil.getJsonFromObject(user));
		}
		return "dayRecord";
	}
	
	@ResponseBody
	@RequestMapping(value="getMembers", produces = "text/html;charset=utf8")
	public String getMembers(String clubId,String searchKey,@RequestParam Map<String, Object> paraMap){
		if(StringUtils.isBlank(clubId)){
			returnResult.setError(true);
			returnResult.setMsg("获取成员信息失败，俱乐部id为空");
			return resultVal();
		}
		//returnResult.setData(clubService.selectMembers(clubId));
		String sql="select m.player_id from t_manager m left join club c on(c.club_manager_id=m.user_id) where c.club_id=?";
		String ManagerPlayerId=dao.getJdbcTemplate().queryForObject(sql,String.class, new Object[]{clubId});
		paraMap.put("ManagerPlayerId", ManagerPlayerId);
		paraMap.put("rows", clubService.selectMembers(clubId,searchKey,paraMap));
		return JacksonUtil.getJsonFromObject(paraMap);
	}
	/**
	 * 出售玩家钻石
	 * @param playerId
	 * @param diamond
	 * @param clubId
	 * @param request
	 * @return
	 * @throws WorkException
	 */
	@RequestMapping(value="agentSendOut", produces = "text/html;charset=utf8")
	@ResponseBody
	public String agentSale(Integer playerId,Integer diamond,String clubId,HttpServletRequest request) throws WorkException{
		if(playerId==null || diamond==null || StringUtils.isBlank(clubId)){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常！请联系管理员");
			return resultVal();
		}
		Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
		if(u!=null && u.getAgentCoin()>diamond){
			if(clubService.agentSendOut(playerId, u, diamond,clubId)>0){
				returnResult.setMsg("发货成功！");
				returnResult.setData(u);
				return resultVal();
			};
		}else{
			returnResult.setError(true);
			returnResult.setMsg("钻石余额不足！");
		}
		return resultVal();
	}
	/**
	 * 销售钻石给下级代理
	 * @param subAgentId
	 * @param diamond
	 * @return
	 * @throws WorkException 
	 */
	@ResponseBody
	@RequestMapping(value="saleToSubAgent", produces = "text/html;charset=utf8")
	public String saleToSubAgent(String subAgentId,Integer diamond) throws WorkException{
		if(subAgentId==null||diamond==null){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常！");
			return resultVal();
		}
		Manager u=(Manager) session.getAttribute(request.getLocalAddr());
		if(u!=null && u.getAgentCoin()>diamond){
			if(clubService.saleToSubAgent(subAgentId, diamond, u.getId())>0){
				returnResult.setMsg("发货成功！");
			}else{
				returnResult.setError(true);
				returnResult.setMsg("发货失败!请联系管理员");
			}
		}else{
			returnResult.setError(true);
			returnResult.setMsg("钻石余额不足！");
		}
		return resultVal();
	}
	
	@RequestMapping(value="changeRemarks", produces = "text/html;charset=utf8")
	@ResponseBody
	public String changeRemarks(Integer mappingId,String comment,HttpServletRequest request) throws WorkException{
		if(mappingId==null || StringUtils.isBlank(comment)){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
			return resultVal();
		}
		if(clubService.changeRemarks(mappingId, comment)>0){
			returnResult.setMsg("修改备注成功!");
		}else{
			returnResult.setError(true);
			returnResult.setMsg("服务器异常!修改备注失败!");
		}
		return resultVal();
	}
	
	@RequestMapping(value="kickOutClub", produces = "text/html;charset=utf8")
	@ResponseBody
	public String kickOutClub(Integer clubId,Integer playerId,HttpServletRequest request){
		if(clubId==null || playerId==null){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
			return resultVal();
		}
		if(clubService.kickOutClub(clubId, playerId)>0){
			returnResult.setMsg("踢出成功!");
		}else{
			returnResult.setError(true);
			returnResult.setMsg("服务器异常!踢出玩家失败!");
		}
		return resultVal();
	}
	@RequestMapping(value="editDefDiamond", produces = "text/html;charset=utf8")
	@ResponseBody
	public String editDefDiamond(Integer diamond,Integer clubId,HttpServletRequest request) throws WorkException{
		if(diamond==null || clubId==null){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
		}else if(clubService.editDefDiamond(clubId, diamond)>0){
			returnResult.setMsg("修改默认额度成功!");
		}
		return resultVal();
	}
	@RequestMapping(value="closeOrOpenPermit", produces = "text/html;charset=utf8")
	@ResponseBody
	public String closePermit(String mappingId,Integer type){
		if(StringUtils.isBlank(mappingId) || type==null){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
		}else if(clubService.closeOrOpenPermit(mappingId, type)>0){
			returnResult.setMsg((type==1?"开启":"关闭")+"权限成功!");
		}
		return resultVal();
	}
	/**
	 * 清空欠费
	 * @param mappingId
	 * @return
	 */
	@RequestMapping(value="clearArrearage", produces = "text/html;charset=utf8")
	@ResponseBody
	public String clearArrearage(String mappingId){
		if(StringUtils.isBlank(mappingId)){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
		}else if(clubService.clearArrearage(mappingId)>0){
			returnResult.setMsg("已结清!");
		}
		return resultVal();
	}
	
	/**
	 * 修改密码
	 * @param mappingId
	 * @return
	 */
	@RequestMapping(value="changePassWord", produces = "text/html;charset=utf8")
	@ResponseBody
	public String changePassWord(String oldPassWord,String newPassWord,HttpServletRequest request){
		if(StringUtils.isBlank(oldPassWord) || StringUtils.isBlank(newPassWord)){
			returnResult.setError(true);
			returnResult.setMsg("服务器获取数据异常");
		}else{
			Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
			if(u!=null && MD5Util.GetMD5Code(oldPassWord).equals(u.getPassword())){
				if(clubService.changePassword(MD5Util.GetMD5Code(newPassWord), u.getId())>0){
					u.setPassword(MD5Util.GetMD5Code(newPassWord));
					returnResult.setMsg("修改密码成功！");
					request.getSession().removeAttribute(request.getLocalAddr());
				}else{
					returnResult.setError(true);
					returnResult.setMsg("服务器异常！");
				}
			}else{
				returnResult.setError(true);
				returnResult.setMsg("原密码错误！");
			}
		}
		return resultVal();
	}
	/**
	 * 查询绑定玩家消费记录
	 * @param clubId
	 * @param searchKey
	 * @return
	 */
	@RequestMapping(value="getMemberRecord", produces = "text/html;charset=utf8")
	@ResponseBody
	public String getMemberRecord(String clubId,String searchKey,Integer page,Integer rows){
		Map<String, Object> map=new HashMap<>();
		Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
		if(u!=null && u.getPlayerId()!=null){
			map.put("ManagerPlayerId", u.getPlayerId());
			map.put("page", page);
			map.put("rows", rows);
		}
		map.put("rows", clubService.getRecordList(clubId, searchKey,map));
		return JacksonUtil.getJsonFromObject(map);
	}
	/**
	 * 查询日报
	 * @return
	 */
	@RequestMapping(value="getDayReport", produces = "text/html;charset=utf8")
	@ResponseBody
	public String getDayReport(String clubId,String searchKey,Integer page,Integer rows){
		Map<String, Object> map=new HashMap<>();
		Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
		if(u!=null && u.getPlayerId()!=null){
			map.put("ManagerPlayerId", u.getPlayerId());
			map.put("managerId",u.getId());
			map.put("page", page);
			map.put("rows", rows);
		}
		map.put("rows", clubService.getReports(map));
		return JacksonUtil.getJsonFromObject(map);
	}
	
	/**
	 * 查询绑定玩家消费记录
	 * @param clubId
	 * @param searchKey
	 * @return
	 */
	@RequestMapping(value="getSaleRecord", produces = "text/html;charset=utf8")
	@ResponseBody
	public String getSaleRecord(@RequestParam Map<String, Object> map){
		Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
		if(u!=null && u.getPlayerId()!=null){
			map.put("ManagerPlayerId", u.getPlayerId());
			map.put("managerId",u.getId());
		}
		map.put("rows", clubService.getSaleRecord(map));
		return JacksonUtil.getJsonFromObject(map);
	}
	
	@RequestMapping(value="getBuyRecord", produces = "text/html;charset=utf8")
	@ResponseBody
	public String getBuyRecord(@RequestParam Map<String, Object> map){
		Manager u=(Manager) request.getSession().getAttribute(request.getLocalAddr());
		if(u!=null && u.getPlayerId()!=null){
			map.put("ManagerPlayerId", u.getPlayerId());
			map.put("managerId",u.getId());
		}
		map.put("rows", clubService.getBuyRecord(map));
		return JacksonUtil.getJsonFromObject(map);
	}
	@RequestMapping(value="searchPlayerInfo", produces = "text/html;charset=utf8")
	@ResponseBody
	public String searchPlayer(@RequestParam Map<String,Object> map){
		Manager u=(Manager) session.getAttribute(request.getLocalAddr());
		if(u!=null && u.getUserType().equals(Constants.MANAGER_TYPE_SUBAGENT)){
			returnResult.setError(true);
			returnResult.setMsg("对不起,您没有权限使用此功能!");
			return resultVal();
		}
		if(map.get("playerId")!=null){
			returnResult.setData(clubService.searchPlayer(map));
		}else{
			returnResult.setError(true);
			returnResult.setMsg("玩家ID为空!");
		}
		return resultVal();
	}
	@RequestMapping(value="checkAgentPhone", produces = "text/html;charset=utf8")
	@ResponseBody
	public String checkAgentPhone(@RequestParam Map<String,Object> map){
		if(map.get("phone")!=null){
			if(clubService.checkPhone(map)>0){
				returnResult.setError(true);
				returnResult.setMsg("该账号已被注册!");
			}else{
				returnResult.setMsg("恭喜!账号可用");
			}
		}else{
			returnResult.setError(true);
			returnResult.setMsg("手机号验证失败!");
		}
		return resultVal();
	}
	
	
	@RequestMapping(value="createSubAgent", produces = "text/html;charset=utf8")
	@ResponseBody
	public String createSubAgent(@RequestParam Map<String,Object> map) throws Exception{
		Manager u=(Manager) session.getAttribute(request.getLocalAddr());
		if(u!=null && u.getUserType().equals(Constants.MANAGER_TYPE_SUBAGENT)){
			returnResult.setError(true);
			returnResult.setMsg("对不起,您没有权限使用此功能!");
			return resultVal();
		}
		if(u!=null && map.get("account")!=null && map.get("clubName")!=null && map.get("playerId")!=null){
			map.put("parentManagerId", u.getId());
			ClubPlayerMapping m=clubService.selectByPlayerId((String) map.get("playerId"));
			if(m!=null){
				returnResult.setError(true);
				returnResult.setMsg("该玩家已绑定代理!请先解绑");
				return resultVal();
			}
			int result=clubService.insertSubAgent(map);
			if(result>0){
				returnResult.setMsg("创建成功!");
			}else if(result==-1){
				returnResult.setError(true);
				returnResult.setMsg("创建失败!钻石额度不足!");
			}else{
				returnResult.setError(true);
				returnResult.setMsg("创建失败!");
			}
		}
		return resultVal();
	}
	
	@RequestMapping(value="getSubAgentPage", produces = "text/html;charset=utf8")
	@ResponseBody
	public String getSubAgentPage(@RequestBody Map<String,Object> param){
		Manager u=(Manager) session.getAttribute(request.getLocalAddr());
		
		if(u!=null && param.get("limit")!=null && param.get("offset")!=null){
			param.put("parentManagerId", u.getId());
			param.put("managerDiamond", u.getAgentCoin());
			clubService.subManager(param);
		}
		return JacksonUtil.getJsonFromObject(param);
	}
}
